<template>
  <div>
    <div class="head">
      <div class="flex">
        <el-button @click="back" icon="el-icon-arrow-left">返回</el-button>
        <span style="margin-left: 10px">抓拍列表</span>
      </div>
      
      <el-button type="primary" class="btn" @click="add">添加抓拍</el-button>
    </div>
    <div class="box">
      <el-table
        :data="tableData"
        border
        v-loading="isTableLoading"
        empty-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        style="width: 100%"
      >
        <el-table-column fixed type="index" align="center" label="序号" width="50" />
        <el-table-column fixed prop="username" align="center" label="姓名" min-width="130" />
        <el-table-column prop="plan_name" align="center" label="课程" min-widthwidth="160" />
        <el-table-column prop="img_url" align="center" label="抓拍图片" min-widthwidth="130">
           
           <template #default="scope">
            <el-image  :src="scope.row.img_url"  style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column prop="create_time" align="center" label="抓拍时间" min-widthwidth="100"></el-table-column>
        
      </el-table>
      <el-pagination
        style="margin-top: 5px"
        @size-change="search"
        @current-change="search"
        :current-page.sync="queryData.page"
        :page-size.sync="queryData.size"
        layout="total, prev, pager, next,sizes,jumper"
        :total="total"
      >
      </el-pagination>
    </div>

     <el-dialog
      :title="'新增抓拍'"
      :visible.sync="isShowAdd"
      width="800px"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        :model="ruleForm"
        style="width: 100%"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
        label-width="100px"
      >
        <el-row :gutter="20">
          <!-- <el-form-item label="所属企业" prop="testId">
          <el-select style="width: 100%" v-model="ruleForm.testId" placeholder="请选择">
            <el-option label="企业" :value="1">企业</el-option>
          </el-select>
        </el-form-item> -->

  

 

          <el-col :span="12">
            <el-form-item label="抓拍图片" prop="professional_certificate_img_url">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                accept=".jpg, .png, .jpeg"
                :before-upload="beforeAvatarUpload"
                :http-request="
                  (file) => {
                    handleAvatarSuccess(file, 'professional_certificate_img_url');
                  }
                "
              >
                <img
                  v-if="ruleForm.professional_certificate_img_url"
                  :src="ruleForm.professional_certificate_img_url"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <p class="prompt">格式JPG、PNG、JPGE，文件大小不超过5M</p>
            </el-form-item>
          </el-col>
  
 
        </el-row>
        <el-card>
 
          <el-card style="margin-bottom: 20px; position: relative" v-for="(item, index) in ruleForm.certs" :key="index">
            <el-form-item
              label="证书分类"
              :prop="'certs.' + index + '.type_id'"
              :rules="{
                required: true,
                message: '请选择证书分类',
                trigger: 'change',
              }"
            >
              <el-select style="width: 100%" v-model="item.type_id" placeholder="请选择">
                <el-option
                  v-for="(item2, index2) in certTypeList"
                  :key="index2"
                  :label="item2.name"
                  :value="item2.id"
                  >{{ item2.name }}</el-option
                >
              </el-select>
            </el-form-item>
            <el-form-item
              label="职业证书编号"
              :prop="'certs.' + index + '.cert_code'"
              :rules="{
                required: true,
                message: '请输入职业证书编号',
                trigger: 'blur',
              }"
            >
              <el-input v-model="item.cert_code" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item
              label="是否永久有效"
              :prop="'certs.' + index + '.expire_type'"
              :rules="{
                required: true,
                message: '请选择是否永久有效',
                trigger: 'change',
              }"
            >
              <el-select style="width: 100%" v-model="item.expire_type" placeholder="请选择">
                <el-option label="是" :value="1">是</el-option>
                <el-option label="否" :value="2">否</el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="证书有效期"
              :prop="'certs.' + index + '.effective'"
              :rules="{
                required: true,
                message: '请选择证书有效期',
                trigger: 'change',
              }"
              v-if="item.expire_type == 2"
            >
              <el-date-picker
                style="width: 100%"
                v-model="item.effective"
                type="daterange"
                range-separator="至"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              label="证书照片"
              :prop="'certs.' + index + '.cert_imgs'"
              :rules="{
                required: true,
                message: '请上传证书照片',
                trigger: 'change',
              }"
            >
              <div class="photo">
                <div class="photo_item">
                  <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    accept=".jpg, .png, .jpeg"
                    :before-upload="beforeAvatarUpload"
                    :http-request="(file) => handleAvatarSuccess(file, 'cert_imgs', index)"
                  >
                    <img v-if="item.cert_imgs" :src="item.cert_imgs" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </div>
              </div>
            </el-form-item>
            <div style="text-align: right">
              <el-button type="danger" icon="el-icon-search" @click="handelDel(index)">删除证书</el-button>
            </div>
          </el-card>
        </el-card>
        <!-- <el-form-item style="margin-top: 20px">
          <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
          <el-button @click="back">取消</el-button>
        </el-form-item> -->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose('ruleForm')">取 消</el-button>
        <el-button type="primary" :loading="subLoading" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="人员培训档案"
      :visible.sync="archiveDialogVisible"
      width="1000px"
      :close-on-click-modal="false"
      @close="currentArchiveData = null; currentPlanStaffId = null"
      top="5vh"
      class="archive-dialog"
    >
      <div v-if="isArchiveLoading" v-loading="true" style="min-height: 300px; width:100%;"></div>
      <div v-if="!isArchiveLoading && currentArchiveData" class="archive-dialog-content" ref="archiveContent">
        <!-- Раздел 1: Заголовок и основная информация -->
        <div class="archive-header">
          <p class="file-number">档案编号: {{ currentArchiveData.file_number }}</p>
          <h2 class="main-title">人员培训档案</h2>
          <div class="info-line">
            <span>姓 名： {{ currentArchiveData.basic_info.name }}</span>
            <span>身份证号： {{ currentArchiveData.basic_info.id_card_number }}</span>
          </div>
          <div class="info-line">
            <span>生成日期： {{ currentArchiveData.generation_date }}</span>
            <span>平台名称 (盖章)： {{ currentArchiveData.platform_name }}</span>
          </div>
        </div>

        <!-- Раздел 2: 基本信息 -->
        <h3 class="section-title">基本信息</h3>
        <table class="info-table">
          <tr>
            <td class="label">姓 名</td><td>{{ currentArchiveData.basic_info.name }}</td>
            <td class="label">性 别</td><td>{{ currentArchiveData.basic_info.gender }}</td>
            <td class="label">年 龄</td><td>{{ currentArchiveData.basic_info.age }}</td>
            <td rowspan="5" style="width: 120px; text-align: center; vertical-align: top; padding-top: 10px;">
              <img v-if="currentArchiveData.basic_info.avatar" :src="currentArchiveData.basic_info.avatar" alt="照片" style="width:100px; height:auto; max-height:120px; border:1px solid #ccc;">
              <div v-else style="width:100px; height:120px; border:1px solid #ccc; display:flex; align-items:center; justify-content:center; margin:auto; background-color: #f0f0f0;">照片</div>
            </td>
          </tr>
          <tr><td class="label">联系电话</td><td>{{ currentArchiveData.basic_info.phone }}</td><td class="label">身份证号</td><td colspan="2">{{ currentArchiveData.basic_info.id_card_number }}</td></tr>
          <tr><td class="label">学 历</td><td>{{ currentArchiveData.basic_info.education }}</td><td class="label">职务/职称</td><td colspan="2">{{ currentArchiveData.basic_info.job_title }}</td></tr>
          <tr><td class="label">部 门</td><td>{{ currentArchiveData.basic_info.department }}</td><td class="label">工 种</td><td colspan="2">{{ currentArchiveData.basic_info.work_type }}</td></tr>
          <tr><td class="label">平台注册时间</td><td>{{ currentArchiveData.basic_info.platform_registration_time }}</td><td class="label">累计课时</td><td colspan="2">{{ currentArchiveData.basic_info.cumulative_hours }}</td></tr>
          <tr><td class="label">所属单位</td><td colspan="5">{{ currentArchiveData.basic_info.company_name }}</td></tr>
        </table>
        
        <!-- Раздел 3: 培训信息 -->
        <h3 class="section-title">培训信息</h3>
        <table class="info-table">
          <tr><td class="label" style="width:120px;">培训名称</td><td>{{ currentArchiveData.training_info.training_name }}</td></tr>
          <tr><td class="label">培训期限</td><td>{{ currentArchiveData.training_info.training_period }}</td></tr>
          <tr><td class="label">起止学习时间</td><td>{{ currentArchiveData.training_info.study_time_range }}</td></tr>
          <tr><td class="label">学习方式</td><td>{{ currentArchiveData.training_info.study_method }}</td></tr>
          <tr><td class="label">课程形式</td><td>{{ currentArchiveData.training_info.course_format }}</td></tr>
        </table>

        <!-- Раздел 4: 培训记录 -->
        <h3 class="section-title">培训记录</h3>
        <table class="info-table">
          <tr><td class="label" style="width:120px;">课程名称</td><td colspan="3">{{ currentArchiveData.training_record_summary.course_name }}</td></tr>
          <tr>
            <td class="label">要求课时</td><td>{{ currentArchiveData.training_record_summary.required_hours }}</td>
            <td class="label">已学课时</td><td>{{ currentArchiveData.training_record_summary.studied_hours }}</td>
          </tr>
          <tr>
            <td class="label">完成学习进度</td><td>{{ currentArchiveData.training_record_summary.learning_progress_percentage }}%</td>
            <td class="label">学时证明</td>
            <td>
                <span v-if="currentArchiveData.file_number">{{ currentArchiveData.file_number }}</span>
                <span v-else>-</span>
            </td>
          </tr>
          <tr>
            <td class="label">考试成绩</td><td>{{ currentArchiveData.training_record_summary.exam_score }}</td>
            <td class="label">是否合格</td><td>{{ currentArchiveData.training_record_summary.is_exam_passed }}</td>
          </tr>
          <tr v-if="currentArchiveData.training_record_summary.retake_exam_score !== null">
            <td class="label">补考成绩</td><td>{{ currentArchiveData.training_record_summary.retake_exam_score }}</td>
            <td class="label">是否合格</td><td>{{ currentArchiveData.training_record_summary.is_retake_exam_passed }}</td>
          </tr>
        </table>
        <div v-if="currentArchiveData.random_photos && currentArchiveData.random_photos.length > 0">
            <div v-for="(photo, index) in currentArchiveData.random_photos" :key="'random-' + index" class="random-photo-item">
              <div class="photo-info">
                <p><strong>随机照片{{ index + 1 }}：</strong> {{ photo.timestamp }}</p>
                <p>课件：{{ photo.courseware_name }}</p>
              </div>
              <div class="photo-image">
                <img :src="photo.image_url" alt="随机照片" style="max-width: 180px; max-height: 120px; border: 1px solid #eee; object-fit: contain;">
              </div>
            </div>
        </div>


        <!-- Раздел 5: 考试试卷名称 -->
        <h3 class="section-title">考试试卷名称</h3>
        <p style="padding-left: 8px; font-size: 10.5pt;">{{ currentArchiveData.exam_paper_name }}</p>

        <!-- Раздел 6: 三级教育培训证明 (если это отдельный имидж, не學時證明) -->
        <div v-if="currentArchiveData.training_record_summary.completion_certificate_url" class="certificate-section">
            <h3 class="section-title">三级教育培训证明</h3>
            <img :src="currentArchiveData.training_record_summary.completion_certificate_url" alt="培训证明" style="max-width: 100%; border: 1px solid #eee; display: block; margin: 10px auto;">
        </div>


        <!-- Раздел 7: 详细课程列表 -->
        <div class="detailed-courses-section">
            <div class="detailed-courses-header">
                <div style="display:flex; justify-content: space-between;">
                    <span>姓名: {{ currentArchiveData.basic_info.name }}</span>
                    <span>身份证号: {{ currentArchiveData.basic_info.id_card_number }}</span>
                </div>
                <h3 class="section-title course-list-main-title">{{ currentArchiveData.detailed_course_list.header_name || currentArchiveData.exam_paper_name }}</h3>
            </div>
            <table class="info-table course-list-table">
              <thead>
                <tr><th>序号</th><th>课程内容</th><th>课时</th><th>讲师</th></tr>
              </thead>
              <tbody>
                <tr v-for="course in currentArchiveData.detailed_course_list.list" :key="course.no">
                  <td>{{ course.no }}</td>
                  <td>{{ course.content_name }}</td>
                  <td>{{ course.hours }}</td>
                  <td>{{ course.lecturer }}</td>
                </tr>
              </tbody>
            </table>
            
            <!-- 课件详情 -->
            <div v-for="course in currentArchiveData.detailed_course_list.list" :key="'courseware-' + course.no" class="courseware-section">
              <h4 class="courseware-title">{{ course.content_name }} - 课件详情</h4>
              <table class="info-table courseware-table" v-if="course.coursewares && course.coursewares.length > 0">
                <thead>
                  <tr><th>序号</th><th>课件名称</th><th>老师</th><th>时长</th></tr>
                </thead>
                <tbody>
                  <tr v-for="(courseware, index) in course.coursewares" :key="courseware.courseware_id">
                    <td>{{ index + 1 }}</td>
                    <td>{{ courseware.title }}</td>
                    <td>{{ courseware.lecturer }}</td>
                    <td>{{ courseware.duration }}</td>
                  </tr>
                </tbody>
              </table>
              <p v-else class="no-courseware">该课程暂无课件</p>
            </div>
        </div>
         <!-- Можно добавить exam_details_summary, если нужно -->
         <div v-if="currentArchiveData.exam_details_summary" class="exam-summary-section">
            <h3 class="section-title">考试总结</h3>
            <table class="info-table">
              <tr><td class="label">培训班名称</td><td>{{currentArchiveData.exam_details_summary.class_name}}</td></tr>
              <tr><td class="label">考生姓名</td><td>{{currentArchiveData.exam_details_summary.examinee_name}}</td></tr>
              <tr><td class="label">考试得分</td><td>{{currentArchiveData.exam_details_summary.score}}</td></tr>
              <tr><td class="label">交卷时间</td><td>{{currentArchiveData.exam_details_summary.exam_submission_time}}</td></tr>
              <tr><td class="label">阅卷人</td><td>{{currentArchiveData.exam_details_summary.grader}}</td></tr>
            </table>
         </div>

         <!-- 考试题目详情 -->
         <div v-if="currentArchiveData.exam_questions_details && currentArchiveData.exam_questions_details.length > 0" class="exam-questions-section">
            <h3 class="section-title">考试题目详情</h3>
            <div v-for="(item, index) in currentArchiveData.exam_questions_details" :key="'exam-' + index">
              <!-- 跳过非题目项（如notice、exam_summary等） -->
              <div v-if="item.type && item.content" class="question-item">
                <div class="question-header">
                  <span class="question-number">第{{ index }}题</span>
                  <span class="question-type">{{ item.type }}</span>
                  <span class="question-score">（{{ item.max_score }}分）</span>
                </div>
                <div class="question-content">
                  <p><strong>题目：</strong>{{ item.content }}</p>
                </div>
                <div v-if="item.options" class="question-options">
                  <p><strong>选项：</strong></p>
                  <div v-for="(optionText, optionKey) in item.options" :key="optionKey" class="option-item">
                    <span class="option-label">{{ optionKey }}.</span>
                    <span class="option-text">{{ optionText }}</span>
                  </div>
                </div>
                <div class="question-answers">
                  <p><strong>正确答案：</strong>
                    <span class="correct-answer">{{ item.correct_answer ? JSON.parse(item.correct_answer).join(', ') : '-' }}</span>
                  </p>
                  <p><strong>学员答案：</strong>
                    <span class="staff-answer" :class="{ 'correct': item.is_correct, 'incorrect': !item.is_correct && item.staff_answer }">
                      {{ item.staff_answer || '未作答' }}
                    </span>
                  </p>
                  <p><strong>得分：</strong>
                    <span class="score-obtained">{{ item.score_obtained }} / {{ item.max_score }}</span>
                  </p>
                </div>
              </div>
            </div>
         </div>

      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="downloadArchivePDF" :loading="isDownloadingPDF" icon="el-icon-download">下载PDF</el-button>
        <el-button @click="archiveDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <training-record-dialog 
      :visible.sync="showTrainingRecordDialog"
      :training-id="$route.query.id"
      :student-list-data="tableData"
      @close="showTrainingRecordDialog = false"
    />
  </div>
</template>

<script>
import { dateFormat } from '../../libs/util';
import {PlanStaffsSnap,PlanRemoveStaff,getTrainingArchiveRecord,upload,SnapSave} from '@/api/manage';
import TrainingRecordDialog from '@/components/TrainingRecordDialog.vue';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export default {
  name: 'cultivate',
  components: { TrainingRecordDialog },
  data() {
    return {
      queryData: {
        useranme: undefined,
        idcard: undefined,
        mobile: undefined,
        study_status: undefined,
        page: 1,
        size: 10,
      }, ruleForm: {
        name: '新增抓拍',
        type: '',
        parent: '',
        department_id: '',
        department_ids: [],
        username: '',
        idcard: '',
        mobile: '',
        edu_id: '',
        level_id: '',
        job_id: '',
        status: '',
        img_url: '',
        professional_certificate_img_url: '',
        appointment_img_url: '',
        account: '',
        job_status: '',
        certs: [],
        snap_status: 0,
        speed_status: 0,
      },rules: {
        
      },
      subLoading: false,
      total: 0,
      isTableLoading: false,
      tableData: [],
      dialogVisible: false,
      tableData2: [],
      isShowAdd: false,
      archiveDialogVisible: false,
      currentArchiveData: null,
      isArchiveLoading: false,
      isDownloadingPDF: false,
      currentPlanStaffId: null,
      showTrainingRecordDialog: false,
    };
  },
  computed: {},
  created() {},
  mounted() {
    this.getList();
  },
  methods: {
    del(item){
      this.$confirm('确认将该学员从本班移除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        PlanRemoveStaff({
          id:item.plan_staff_id
        }).then((res) => {
          this.$message({
            type: 'success',
            message: '移除成功',
          });
          this.getList();
        });
      });
    },
    search() {
      this.queryData.page = 1;
      this.getList();
    },
    studentSnap(item) {
      console.log(1111);
      this.$router.push({
        path: '/company/studentList/index',
        query: {
          id: item.id,
        },
      });
    },
    
    reset() {
      this.queryData.name = '';
      this.queryData.idCard = '';
      this.queryData.phone = '';
      this.queryData.status = '';
      this.search();
    },
    add() {
      this.isShowAdd = true;
    },
    addOk() {
      this.isShowAdd = false;
    },
    getList() {
      this.isTableLoading = true;
      this.queryData.id = this.$route.query.id;
      this.queryData.plan_staff_id = this.$route.query.plan_staff_id;
      PlanStaffsSnap(this.queryData).then(res=>{
        this.tableData = res.data.list
        this.total = res.data.total
        this.isTableLoading = false
      }).catch(() => {
        this.isTableLoading = false;
      })

    },
    back() {
      this.$router.back();
    },
    handleAvatarSuccess(e, type, index) {
      let obj = new FormData();
      obj.append('file', e.file);
      upload(obj).then((res) => {
        if (type != 'cert_imgs') {
          this.ruleForm[type] = res.data.url;
        } else {
          this.$set(this.ruleForm.certs[index], 'cert_imgs', res.data.url);
          // this.ruleForm.certs[index].cert_imgs = res.data.url;
        }
      });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isLt2M;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.subLoading = true;
          this.ruleForm.id = this.$route.query.id;
          this.ruleForm.plan_staff_id = this.$route.query.plan_staff_id;
          
          SnapSave(this.ruleForm)
            .then((res) => {
              this.$message.success('添加成功');
              this.getList();
              this.$refs[formName].resetFields();
              this.isShowAdd = false;
              this.subLoading = false;
            })
            .catch(() => {
              this.subLoading = false;
            });
        } else {
          this.$message.error('请正确填写！');
          return false;
        }
      });
    },

    handleClose() {
      this.ruleForm = {
        department_id: '',
        department_ids: [],
        username: '',
        idcard: '',
        mobile: '',
        edu_id: '',
        level_id: '',
        job_id: '',
        status: '',
        img_url: '',
        account: '',
        appointment_img_url: '',
        professional_certificate_img_url: '',
        job_status: '',
        certs: [],
        snap_status: 0,
        speed_status: 0,
      };
      this.isShowAdd = false;
    },
    async openArchiveDialog(row) {
      if (!row.plan_staff_id) {
        this.$message.error('学员计划ID不存在，无法查看档案。');
        return;
      }
      this.currentArchiveData = null;
      this.isArchiveLoading = true;
      this.archiveDialogVisible = true;
      this.currentPlanStaffId = row.plan_staff_id;
      try {
        const res = await getTrainingArchiveRecord({ plan_staff_id: row.plan_staff_id });
        if (res.status === 200 && res.data) {
          this.currentArchiveData = res.data;
        } else {
          this.$message.error(res.msg || '获取档案详情失败');
          this.archiveDialogVisible = false; 
        }
      } catch (error) {
        console.error('获取档案详情错误:', error);
        this.$message.error('获取档案详情发生错误');
        this.archiveDialogVisible = false;
      } finally {
        this.isArchiveLoading = false;
      }
    },
    async downloadArchivePDF() {
      if (!this.currentArchiveData) {
        this.$message.error('请先查看档案内容');
        return;
      }
      
      this.isDownloadingPDF = true;
      this.$message.info('正在生成PDF，请稍候...');
      
      try {
        // 获取档案内容DOM元素
        const element = this.$refs.archiveContent;
        if (!element) {
          this.$message.error('档案内容未加载完成');
          return;
        }
        
        // 暂时隐藏滚动条，确保完整截图
        const originalOverflow = element.style.overflow;
        element.style.overflow = 'visible';
        
        // 使用html2canvas将DOM转换为canvas
        const canvas = await html2canvas(element, {
          scale: 2, // 提高清晰度
          useCORS: true, // 允许跨域图片
          allowTaint: true,
          backgroundColor: '#ffffff',
          scrollX: 0,
          scrollY: 0,
          width: element.scrollWidth,
          height: element.scrollHeight
        });
        
        // 恢复原始样式
        element.style.overflow = originalOverflow;
        
        // 创建PDF文档 (A4大小)
        const pdf = new jsPDF('p', 'mm', 'a4');
        const imgData = canvas.toDataURL('image/png');
        
        // 计算图片在PDF中的尺寸
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = pdf.internal.pageSize.getHeight();
        const imgWidth = pdfWidth;
        const imgHeight = (canvas.height * pdfWidth) / canvas.width;
        
        let position = 0;
        
        // 如果内容高度超过一页，需要分页
        if (imgHeight > pdfHeight) {
          // 分页处理
          let remainingHeight = imgHeight;
          
          while (remainingHeight > 0) {
            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
            remainingHeight -= pdfHeight;
            position -= pdfHeight;
            
            if (remainingHeight > 0) {
              pdf.addPage();
            }
          }
        } else {
          // 单页处理
          pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
        }
        
        // 生成文件名
        const today = new Date();
        const dateStr = today.getFullYear() + 
                       String(today.getMonth() + 1).padStart(2, '0') + 
                       String(today.getDate()).padStart(2, '0');
        const idCardLast4 = this.currentArchiveData.basic_info.id_card_number.slice(-4);
        const fileName = `人员培训档案_${this.currentArchiveData.basic_info.name}_${idCardLast4}_${dateStr}.pdf`;
        
        // 下载PDF
        pdf.save(fileName);
        
        this.$message.success('PDF下载成功');
      } catch (error) {
        console.error('生成PDF错误:', error);
        this.$message.error('生成PDF失败，请稍后重试');
      } finally {
        this.isDownloadingPDF = false;
      }
    },
    openTrainingRecordDialog() {
      if (!this.$route.query.id) {
        this.$message.error('无效的培训计划ID');
        return;
      }
      this.showTrainingRecordDialog = true;
    },
  },
};
</script>

<style scoped>
.head {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  background: #ffffff;
  border-radius: 5px;
  padding: 20px;
  padding-bottom: 0px;
}
.input {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 20px;
}
.input > span {
  font-size: 12px;
  flex-shrink: 0;
}
.btn {
  margin-bottom: 20px;
}
.box {
  width: 100%;
  background: #ffffff;
  border-radius: 5px;
  padding: 20px;
  margin-top: 20px;
}
.action {
  display: flex;
  align-items: center;
  justify-content: center;
}
.action span {
  color: #0256ff;
  font-size: 12px;
  cursor: pointer;
  margin: 0 8px;
}
.flex {
  width: 100%;
  align-items: center;
  margin-bottom: 20px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
}
.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  line-height: 100px;
  text-align: center;
}
/* Styles for Archive Dialog */
.archive-dialog ::v-deep .el-dialog__body {
  padding: 10px 20px 30px 20px;
  max-height: 80vh;
  overflow-y: auto;
}

.archive-dialog-content {
  font-family: SimSun, '宋体', sans-serif;
  color: #000;
  font-size: 12pt;
  line-height: 1.6;
  /* 确保PDF生成时的最佳显示效果 */
  print-color-adjust: exact;
  -webkit-print-color-adjust: exact;
}
.archive-header {
  text-align: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #ccc;
  padding-bottom: 15px;
}
.archive-header .file-number {
  text-align: right;
  font-size: 10pt;
  margin-bottom: 5px;
  color: #555;
}
.archive-header .main-title {
  font-size: 22pt;
  font-weight: bold;
  margin-bottom: 15px;
  color: #000;
}
.archive-header .info-line {
  display: flex;
  justify-content: space-between;
  width: 90%;
  margin: 8px auto;
  font-size: 12pt;
}

.section-title {
  font-size: 14pt;
  font-weight: bold;
  margin-top: 25px;
  margin-bottom: 15px;
  text-align: left;
  border-bottom: 2px solid #000;
  padding-bottom: 8px;
  color: #000;
  /* 避免标题在页面间断开 */
  page-break-after: avoid;
}
.course-list-main-title {
    text-align: center !important;
    border-bottom: none !important;
    font-size: 16pt !important;
    margin-bottom: 10px !important;
}


.info-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  font-size: 10.5pt;
  border: 1px solid #000;
  /* 避免表格在页面间断开 */
  page-break-inside: avoid;
}
.info-table th, .info-table td {
  border: 1px solid #000;
  padding: 8px 10px;
  text-align: left;
  vertical-align: middle;
  line-height: 1.5;
}
.info-table td.label {
  font-weight: normal;
  background-color: transparent;
  width: 130px;
  text-align: left;
  padding-left: 15px;
}

.random-photo-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.random-photo-item .photo-info {
  flex-grow: 1;
  padding-right: 15px;
}
.random-photo-item .photo-info h4 {
  margin-top: 0;
  margin-bottom: 8px;
  font-size: 12pt;
}
.random-photo-item .photo-info p {
  margin: 4px 0;
  font-size: 10pt;
  color: #333;
}
.random-photo-item .photo-image img{
  border-radius: 3px;
}


.certificate-section {
    margin-top: 20px;
    margin-bottom: 20px;
}
.certificate-section img {
  display: block;
  margin: 10px auto;
  border: 1px solid #ccc;
  max-width: 90%;
  height: auto;
}

.detailed-courses-section {
    margin-top: 20px;
}
.detailed-courses-header {
  margin-bottom: 10px;
  font-size: 10.5pt;
  padding: 0 8px;
}
.course-list-table th {
  background-color: transparent;
  text-align: center;
  font-weight: bold;
}
.course-list-table td {
  text-align: center;
}
.course-list-table td:nth-child(2) {
  text-align: left;
  padding-left: 15px;
}
.exam-summary-section {
    margin-top: 20px;
}

/* 课件详情样式 */
.courseware-section {
    margin-top: 15px;
    margin-bottom: 20px;
}
.courseware-title {
    font-size: 12pt;
    font-weight: bold;
    margin-bottom: 10px;
    color: #333;
    border-left: 4px solid #409EFF;
    padding-left: 10px;
}
.courseware-table th {
    background-color: #f5f7fa;
    text-align: center;
    font-weight: bold;
}
.courseware-table td {
    text-align: center;
}
.courseware-table td:nth-child(2) {
    text-align: left;
    padding-left: 15px;
}
.no-courseware {
    color: #999;
    font-style: italic;
    text-align: center;
    padding: 10px;
    background-color: #f9f9f9;
    border: 1px solid #eee;
    border-radius: 4px;
}

/* 考试题目详情样式 */
.exam-questions-section {
    margin-top: 20px;
}
.question-item {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background-color: #fafafa;
    /* 避免题目在页面间断开 */
    page-break-inside: avoid;
}
.question-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-weight: bold;
}
.question-number {
    color: #409EFF;
    margin-right: 10px;
    font-size: 12pt;
}
.question-type {
    background-color: #409EFF;
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 10pt;
    margin-right: 10px;
}
.question-score {
    color: #f56c6c;
    font-size: 10pt;
}
.question-content {
    margin-bottom: 12px;
    padding: 8px;
    background-color: white;
    border-radius: 4px;
    border-left: 3px solid #409EFF;
}
.question-content p {
    margin: 0;
    line-height: 1.6;
}
.question-options {
    margin-bottom: 12px;
}
.question-options > p {
    margin-bottom: 8px;
    font-weight: bold;
}
.option-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 6px;
    padding: 4px 8px;
    background-color: white;
    border-radius: 4px;
}
.option-label {
    font-weight: bold;
    margin-right: 8px;
    color: #606266;
    min-width: 20px;
}
.option-text {
    flex: 1;
    line-height: 1.5;
}
.question-answers {
    background-color: white;
    padding: 10px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
}
.question-answers p {
    margin: 6px 0;
    display: flex;
    align-items: center;
}
.correct-answer {
    color: #67c23a;
    font-weight: bold;
    margin-left: 8px;
}
.staff-answer {
    margin-left: 8px;
    padding: 2px 6px;
    border-radius: 3px;
}
.staff-answer.correct {
    background-color: #f0f9ff;
    color: #67c23a;
    font-weight: bold;
}
.staff-answer.incorrect {
    background-color: #fef0f0;
    color: #f56c6c;
    font-weight: bold;
}
.score-obtained {
    margin-left: 8px;
    font-weight: bold;
    color: #409EFF;
}

/* PDF生成优化样式 */
.archive-dialog-content img {
  /* 确保图片在PDF中正确显示 */
  max-width: 100% !important;
  height: auto !important;
  page-break-inside: avoid;
}

.section-title {
  /* 避免标题在页面间断开 */
  page-break-after: avoid;
}

.info-table {
  /* 避免表格在页面间断开 */
  page-break-inside: avoid;
}

.question-item {
  /* 避免题目在页面间断开 */
  page-break-inside: avoid;
}
</style>
